import os
from django.shortcuts import render_to_response
from django.http import HttpResponse
from dat_handler.models import DatFileForm
from django.conf import settings


def index(request, template=None, form_class=None):
    """Handles posting of EnergyPro's dat file"""
    if template is None: template = 'templates/index.html'
    if form_class is None: form_class = DatFileForm
    if request.method == 'POST':
        form = form_class(request.POST, request.FILES)
        if form.is_valid():
            from title24_local_ordinance import main_module, dat_reader
            calculator = dat_reader.parse_dat_file(request.FILES['dat_file'])
            calculator.proj_name = "Sample Project Name"
            pdf_path = main_module.make_pdf(
                calculator,
                target_dir=settings.PDF_FILE_DIR
            )
            response = HttpResponse(mimetype='application/pdf')
            response['Content-Disposition'] = \
                    'attachment; filename=%s' % os.path.basename(pdf_path)
            pdf = file(pdf_path, 'r')
            response.write(pdf.read())
            return response
    else:
        form = form_class()

    return render_to_response(template, {
        'form': form,
    })
